import usb
import sys
########################################################################
class USBDetector():
    """Detects all USB Mass Storage devices"""
    
    #----------------------------------------------------------------------
    def search(self):
        classToScan = 8 #see http://www.usb.org/developers/defined_class for deviceClasses
        subClassToScan = 6 #SCSI
        found = []

        #Note that device class could be determined in two ways:
        #1) By device descriptor (only one conf per device)
        #2) By device configuration interface (let device to choose)

        for bus in usb.busses():
            for dev in bus.devices:
#               if dev.deviceClass == classToScan:
#                   found.append(self.addDevice(dev))
#                   devNo += 1
#               else:
                for conf in dev.configurations:
                    for iList in conf.interfaces:
                        for inter in iList:
                            iClass = inter.interfaceClass
                            iSubClass = inter.interfaceSubClass
                            if iClass == classToScan and iSubClass == subClassToScan:
                                found.append(self.addDevice(dev))

        return found

    #----------------------------------------------------------------------
    def addDevice(self, dev):
        newDevice = USBDevice()
        newDevice.setVendor((hex(dev.idVendor)[2:-1]).rjust(4,'0'))
        newDevice.setProduct((hex(dev.idProduct)[2:-1]).rjust(4,'0'))
        newDevice.setSerial(dev.open().getString(3,255))

        return newDevice

class USBDevice():
    #----------------------------------------------------------------------
    def setVendor(self, vendor):
        self.vendor = vendor
        
    #----------------------------------------------------------------------
    def getVendor(self):
        return self.vendor

    #----------------------------------------------------------------------
    def setProduct(self, product):
        self.product = product
        
    #----------------------------------------------------------------------
    def getProduct(self):
        return self.product

    #----------------------------------------------------------------------
    def setSerial(self, serial):
        self.serial = serial
        
    #----------------------------------------------------------------------
    def getSerial(self):
        return self.serial
